import {Component, Input, OnDestroy} from "@angular/core";

/**
 * 在指定 delay 时间后显示 loading 界面。默认不显示
 * 用法示例：
 * <dhl-loading *ngIf="isBusy" [isRunning]="isBusy"></dhl-loading>
 */
@Component({
    selector: 'dhl-loading',
    styleUrls: ['loading.scss'],
    templateUrl: 'loading.html',
})
export class LoadingComponent implements OnDestroy {
    public visible: boolean = false;
    public timeout: any;

    @Input()
    public loadingText: string = '';

    @Input()
    public delay: number = 500;

    @Input() cssClass: string;

    @Input()
    public set isRunning(value: boolean) {
        if (!value) {
            this.cancel();
            this.visible = false;
            return;
        }

        if (this.timeout) {
            return;
        }

        this.timeout = setTimeout(() => {
            this.visible = true;
            this.cancel();
        }, this.delay);
    }

    private cancel(): void {
        clearTimeout(this.timeout);
        this.timeout = undefined;
    }

    ngOnDestroy(): any {
        this.cancel();
    }
}
